package util;
/*
 *ClassName:FileUtil
 *Description:工具类：用于文本文件的合并，读取以及获得某目录下的文本文件名称
 *@author:可爱的大鸭子
 */

import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class FileUtil {
    /*将多个文本文件合并为一个文件*/
    public static void merge(String outFileName, List<String> inFileNames) throws IOException{
        FileWriter writer=new FileWriter(outFileName,false);    //false不覆盖
        for(String inFileName :inFileNames ){
            try {
                String txt= readToString(inFileName);
                writer.write(txt);
                System.out.println(txt);
            }catch (Exception e){
            }
        }
        writer.close();
    }
    /*读取文本文件内容到字符串*/
    public static String readToString(String fileName) throws IOException {
        String encoding = "UTF-8";
        File file = new File(fileName);
        Long filelength = file.length();
        byte[] filecontent = new byte[filelength.intValue()];
        FileInputStream in = new FileInputStream(file);
        in.read(filecontent);
        in.close();
        return new String(filecontent, encoding);   //指定编码
    }

    /*查找某个目录下所有的文件名称，返回List*/
    public static List<String> getFiles(String path) {
        List<String> files = new ArrayList<String>();
        File file = new File(path);
        File[] tempList = file.listFiles();     //列出所有文件
        for (int i = 0; i < tempList.length; i++) {
            if (tempList[i].isFile()) {         //如果是文件
                files.add(tempList[i].toString());//文件转为字符串
            }
            if (tempList[i].isDirectory()) {//如果是文件夹
                files.addAll(getFiles(tempList[i].toString()));
            }
        }
        return files;
    }
}
